<template>
  <el-dialog v-model="isShowDialog"
             :before-close="handleClose"
             :title="title"
             draggable
             width="80%"
             append-to-body
  >
    <div class="justify-content items-center" style="margin-bottom: 15px">
      <div class="plan">
        <span class="information"></span>
        <span class="informationText">采购信息</span>
      </div>
    </div>
    <el-form :inline="true" ref="formRef" :disabled="isView" :model="saveParams" label-width="100px" :rules="rules">
      <div style="display: flex;flex-wrap: wrap">
        <el-col :span="6">
          <el-form-item label="采购单号">
            <el-input v-model="saveParams.purchaseCode" @input="saveParams.purchaseCode=limitCharAndNumber(saveParams.purchaseCode)" placeholder="填写或自动生成" clearable/>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="所属仓库" prop="warehouseId">
            <el-select
                :disabled="saveParams.purchaseId"
                clearable
                v-model="saveParams.warehouseId"
                @change="changeWarehouse"
            >
              <template v-for="(item,index) in warehouseList" :key="index">
                <el-option :label="item.warehouseName" :value="item.warehouseId"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="供应商名称" prop="vendorId">
            <el-select v-model="saveParams.vendorId" style="width: 100%"
                       clearable placeholder="供应商名称">
              <el-option
                  v-for="item in vendorList"
                  :key="item.vendorId"
                  :label="item.vendorName"
                  :value="item.vendorId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商编码">
            <el-input v-model="saveParams.vendorCode" placeholder="自动生成" clearable disabled/>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="配送方式">
            <el-input v-model="saveParams.delivery" placeholder="配送方式" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货人">
            <el-input v-model="saveParams.shipmentByName" placeholder="发货人" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式">
            <el-input v-model="saveParams.shipmentPhone"
                      @input="saveParams.shipmentPhone=limitIntNumber(saveParams.shipmentPhone)" :maxlength="11" placeholder="联系方式"
                      clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货地址">
            <el-input v-model="saveParams.shipmentAddress" placeholder="发货地址" clearable/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="备注" style="width: 92%">
            <el-input type="textarea" :rows="3" v-model="saveParams.remark" placeholder="备注" clearable/>
          </el-form-item>
        </el-col>

      </div>

    </el-form>

    <div class="justify-content items-center" style="margin:15px 0">
      <div class="plan">
        <span class="information"></span>
        <span class="informationText">商品信息</span>
      </div>
    </div>
    <el-row v-if="!isView">
      <el-button icon="Plus" type="primary" @click="handleAdd">新建商品</el-button>
      <el-button icon="Delete" type="danger" @click="handleDel">删除所选</el-button>
      <el-button type="primary" @click="clickSetNum">采购数量批量设置</el-button>
      <el-button type="primary" @click="clickSetPrice">采购单价批量设置</el-button>
    </el-row>
    <vxe-table
        ref="tableRef"
        border
        style="margin-top: 10px;"
        align="center"
        :data="tableList"
        height="300"
        :checkbox-config="{ trigger:'row'}"
        :edit-rules="validRules"
        :row-config="{isCurrent: true, isHover: true}"
        show-footer
        :footer-method="footerMethod"
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column type="seq" width="80" title="序号"></vxe-column>
      <vxe-column field="skuCode" width="200" title="SKU编号"></vxe-column>
      <vxe-column field="skuName" width="220" title="商品名称"></vxe-column>
      <vxe-column field="coverUrl" width="180" title="商品图片">
        <template #default="{row}">
          <ImagePreview v-if="row.coverUrl" :width="150" :height="50" :src="row.coverUrl" ></ImagePreview>
        </template>
      </vxe-column>
      <vxe-column field="skuType" width="120" title="商品分类"></vxe-column>
      <vxe-column field="skuAttr" width="120" title="属性"></vxe-column>
      <vxe-column field="purchaseNum" width="120" title="采购数量">
        <template #header>
          <span style="color: red;">*</span>采购数量
        </template>
        <template #default="{row}">
          <el-input v-model="row.purchaseNum" @change="countTotal(row)" :disabled="isView"
                    @input="row.purchaseNum=limitIntNumber(row.purchaseNum)" clearable/>
        </template>
      </vxe-column>
      <vxe-column field="purchasePrice" width="120" title="采购单价">
        <template #header>
          <span style="color: red;">*</span>采购单价
        </template>
        <template #default="{row}">
          <el-input v-model="row.purchasePrice" @change="countTotal(row)" :disabled="isView"
                    @input="row.purchasePrice=limitNumber(row.purchasePrice)" clearable/>
        </template>
      </vxe-column>
      <vxe-column field="totalPurchaseMoney" width="120" title="采购金额">
        <template #header>
          <span style="color: red;">*</span>采购金额
        </template>
        <template #default="{row}">
          <el-input v-model="row.totalPurchaseMoney" @change="contPice(row)" :disabled="isView"
                    @input="row.totalPurchaseMoney=limitNumber(row.totalPurchaseMoney)" clearable/>
        </template>
      </vxe-column>
      <vxe-column field="brand" width="120" title="品牌"></vxe-column>
      <vxe-column field="barcode" width="120" title="条码"></vxe-column>

    </vxe-table>
    <SelB2bPurchaseCommodity v-if="openSelDialog" :openSelDialog="openSelDialog"
                             :companyId="sysUserInfo.companyId"
                             :warehouseId="saveParams.warehouseId"
                             :filterData="tableList"
                             @closeSelDialog="closeSelDialog"></SelB2bPurchaseCommodity>

    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" v-if="!isView" @click="clickSave"> 保存 </el-button>
          <el-button type="primary" v-if="!isView" @click="clickSubmit"> 提交 </el-button>
          <el-button @click="handleClose">取消</el-button>
        </span>
    </template>

  </el-dialog>
  <!--  批量设置采购数量-->
  <el-dialog v-model="isShowBatchSetNum"
             :before-close="handleCloseSetNum"
             title="批量设置采购数量"
             draggable
             width="400px"
             append-to-body>
    <el-form>
      <el-form-item label="采购数量">
        <el-input v-model="purchaseNums"  @input="purchaseNums=limitIntNumber(purchaseNums)"  clearable placeholder="采购数量"/>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="clickSaveNum"> 确认 </el-button>
          <el-button @click="handleCloseSetNum">取消</el-button>
        </span>
    </template>
  </el-dialog>
  <!--  批量设置采购单价-->
  <el-dialog v-model="isShowBatchSetPrice"
             :before-close="handleCloseSetPrice"
             title="批量设置采购单价"
             draggable
             width="400px"
             append-to-body>
    <el-form>
      <el-form-item label="采购单价">
        <el-input v-model="purchasePrices"  @input="purchasePrices=limitNumber(purchasePrices)" clearable placeholder="采购单价"/>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="clickSavePrice"> 确认 </el-button>
          <el-button @click="handleCloseSetPrice">取消</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {getVendorFilter, skuB2bPurchaseHeaderCommit, skuB2bPurchaseHeaderSave} from "@/api/scApi";
import {getCurrentInstance, onMounted, ref} from "vue";
import SelB2bPurchaseCommodity from "@/views/procure/B2bPurchase/componet/selB2bPurchaseCommodity.vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {limitCharAndNumber} from "@/utils/shuangcheng";
import {getCompanySelect, getWarehouseSelect} from "@/api/system/user";

const {proxy} = getCurrentInstance()
let tableList = ref([])
let saveParams = ref({})
let purchaseNums = ref("") //批量设置采购数量的值
let purchasePrices = ref("") //批量设置采购单价的值
// 表单校验
const rules = ref({
  vendorId: [{required: true, message: "供应商不能为空", trigger: "blur"}],
  warehouseId: [{required: true, message: "所属仓库不能为空", trigger: "change"}],
});
const validRules = ref({
  purchaseNum: [
    {required: true, message: '采购数量不能为空'},
  ],
  purchasePrice: [
    {required: true, message: '采购单价不能为空'},
  ],
  totalPurchaseMoney: [
    {required: true, message: '采购金额不能为空'},
  ],
})

const props = defineProps({
  isShowDialog: {
    type: Boolean,
    default: false
  },
  title: {
    type: String
  },
  warehouseList: {type: Array},
  detailData: {type: Object},
  isView: {type: Boolean}
})

const emits = defineEmits(['cancel'])

function handleClose() {
  emits('cancel')
}

//添加商品事件处理
let openSelDialog = ref(false)

function handleAdd() {

  if(!saveParams.value.warehouseId  ){
    proxy.$modal.msgWarning("请先选择仓库!")
    return
  }

  openSelDialog.value = true
}

function closeSelDialog(data) {
  openSelDialog.value = false
  if (data) {
    tableList.value = [...tableList.value, ...data]
  }
}

//获取供应商下拉
let vendorList = ref([])

function getVendorList() {
  getVendorFilter({
    'companyId': sysUserInfo.companyId,
    'warehouseId':saveParams.value.warehouseId,
  }).then(res => {
    if (res.code === 200) {
      vendorList.value = res.data
    }
  })
}

onMounted(() => {
  if (JSON.stringify(props.detailData) != '{}') {
    saveParams.value = props.detailData.header
    tableList.value = props.detailData.details
  }

  getWarehouse()
  if(saveParams.value.purchaseId){
    getVendorList()
  }
})

//删除所选
function handleDel() {
  let selRows = proxy.$refs.tableRef.getCheckboxRecords()
  let a = tableList.value
  let filtered = a.filter(obj => !selRows.some(bObj => bObj.skuId === obj.skuId));
  tableList.value = filtered
}

const clickSubmit = async () => {
  const $table = proxy.$refs.tableRef

  if ($table) {
    const errMap = await $table.validate(true)
    if (errMap) {
      console.log('校验失败！')
    } else {
      console.log('校验成功！')
      proxy.$refs.formRef.validate((valid) => {
        if (valid) {
          let params = {
            header: saveParams.value,
            details: tableList.value
          }
          skuB2bPurchaseHeaderCommit(params).then(res => {
            if (res.code === 200) {
              proxy.$modal.msgSuccess('保存成功')
              emits('cancel', true)
            }
          })
        }
      })
    }
  }
}

const clickSave= async () => {
  const $table = proxy.$refs.tableRef

  if ($table) {
    const errMap = await $table.validate(true)
    if (errMap) {
      console.log('校验失败！')
    } else {
      console.log('校验成功！')
      proxy.$refs.formRef.validate((valid) => {
        if (valid) {
          let params = {
            header: saveParams.value,
            details: tableList.value
          }
          skuB2bPurchaseHeaderSave(params).then(res => {
            if (res.code === 200) {
              proxy.$modal.msgSuccess('保存成功')
              emits('cancel', true)
            }
          })
        }
      })
    }
  }
}

//计算总额
function countTotal(row) {
  if (row.purchaseNum && row.purchasePrice) {
    row.totalPurchaseMoney = (row.purchaseNum * row.purchasePrice).toFixed(2)
  }
  proxy.$refs.tableRef.updateFooter()
}

//计算单价
function contPice(row) {
  if (row.totalPurchaseMoney && row.purchaseNum) {
    row.purchasePrice = (row.totalPurchaseMoney / row.purchaseNum).toFixed(2)
  }
  proxy.$refs.tableRef.updateFooter()
}

//批量设置采购数量
let isShowBatchSetNum = ref(false)
function clickSetNum() {
  isShowBatchSetNum.value = true
}
function handleCloseSetNum() {
  isShowBatchSetNum.value = false
}
function clickSaveNum(){
  tableList.value=tableList.value.map(item=>{
    item.purchaseNum =purchaseNums.value
    item.totalPurchaseMoney = item.purchaseNum * item.purchasePrice
    return item
  })
  isShowBatchSetNum.value = false
}

//批量设置采购单价
let isShowBatchSetPrice = ref(false)
function clickSetPrice() {
  isShowBatchSetPrice.value = true
}
function handleCloseSetPrice() {
  isShowBatchSetPrice.value = false
}
function clickSavePrice(){
  tableList.value=tableList.value.map(item=>{
    item.purchasePrice =purchasePrices.value
    item.totalPurchaseMoney = item.purchaseNum * item.purchasePrice
    return item
  })
  isShowBatchSetPrice.value = false
}
function footerMethod({ columns, data }){
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return '合计'
      }
      if (['purchaseNum','totalPurchaseMoney'].includes(column.field)) {
        return sumNum(data, column.field)
      }
      return null
    })
  ]
}
const sumNum = (list,field) => {
  let count = 0
  list.forEach(item => {
    if(item[field]){
      count += Number(item[field])
    }
  })
  return count.toFixed(2)
}

//获取仓库下拉数据
let warehouseList = ref([])
const sysUserInfo=JSON.parse(localStorage.getItem("userInfo"))
function getWarehouse(){
  getWarehouseSelect({'companyId': sysUserInfo.companyId}).then(res => {
    warehouseList.value = res.data
  })
}

function changeWarehouse(){
  saveParams.value.vendorId=''
  vendorList.value=[]
  tableList.value=[]
  getVendorList()
}


</script>

<style scoped lang="scss">

</style>